package com.fly.service;

import com.fly.persistence.DataEntity;
import com.fly.persistence.MyJpaRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author Fly
 * @Description
 * @Date Created in 14:43 2017/9/13
 * @Modified by
 */
public abstract class CurdService<D extends MyJpaRepository<T,Long>,T extends DataEntity<T>> {

    protected final static String SORT_DESC = "desc";

    @Autowired
    private D dao;

    /**
     * 获取单条数据
     * @param id
     * @return
     */
    public T findById(Long id){
        return dao.findById(id).get();
    }

    /**
     * 获取列表
     * @return
     */
    public List<T> findAll(){
        return dao.findAll();
    }

    /**
     * 分页按条件获取列表
     */
    public Page<T> findAll(T entity, Specification<T> specification){
        String querySort = entity.getSort();
        if (querySort == null || querySort.length() == 0) {
            querySort = "id";
        }
        Sort sort;
        if (SORT_DESC.equals(entity.getOrder())) {
            sort = new Sort(Sort.Direction.DESC, querySort);
        } else {
            sort = new Sort(Sort.Direction.ASC, querySort);
        }
        Pageable pageable = PageRequest.of(entity.getPageIndex(), entity.getLimit(), sort);
        return dao.findAll(specification, pageable);
    }
    /**
     * 删除
     * @param id
     */
    @Transactional(rollbackFor = Exception.class)
    public void delete(Long id){
        dao.deleteById(id);
    }
    /**
     * 保存实体类
     * @param entity
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public T save(T entity){
        if(entity.getIsNewRecord()){
       //     entity.preInsert();
        }else {
            T t = findById(entity.getId());
            entity.setCreateBy(t.getCreateBy());
            entity.setCreateDate(t.getCreateDate());
       //     entity.preUpdate();
        }
        return dao.save(entity);
    }

}
